<template>
    <div>
        <div class="jnpf-tree-wrapper" v-if="activeMenu.showTree">
            <div class="jnpf-tree-title" @click="collapse = !collapse">
                <i class="el-icon-caret-right" v-if="!collapse"></i>
                <i class="el-icon-caret-bottom" v-else></i>
                {{ activeMenu.label }}
            </div>
            <el-tree v-if='collapse' :data="treeData" ref="treeBox" :props="treeProps" default-expand-all highlight-current
                :expand-on-click-node="false" @node-click="handleNodeClick" :node-key="treeProps.value">
                <!-- <template #default="{ node, data }">
                    <div class="custom-tree-node" @contextmenu.stop.prevent='contexMenuEvent(node, data)'>
                        <div class="custom-tree-node-content">
                            <div v-if="data.type == 0" class="custom-tree-node-content">
                                <es-icon name="wenjian_weixuanzhong" :size="16" />
                                {{ data.label }}
                            </div>
                            <el-tree-select v-model="data.id" value-key="id" node-key="id" :data="featureWebData"
                                :props="treeProps" :render-after-expand="false" style="width: 100%" size="small"
                                v-if="data.type == 1" />
                        </div>
                    </div>
                </template> -->
            </el-tree>
            <!-- <ContextMenuCom :baseItems="menuContent"></ContextMenuCom> -->
        
        </div>
    </div>
   

</template>

<script>
import { getConfig, getList, getFeatureSelector, getDictionaryDataSelector, getDepartmentSelector, getDataInterfaceRes } from '@/api/jnpf'
// import JNPFMarker from './jnpfMarker'
// import html2canvas from 'html2canvas'
export default {
    components: {
        // ContextMenuCom
    },
    props: {
        activeMenu: {
            type: Object,
            default: {}
        },
        xbsjEarthUi: {
            type: Object
        }
    },
    data() {
        return {
            collapse: true,
            treeData: [],
            moduleId: '',
            featureWebData: [],
            treeActiveId: '',
            treeProps: {
                children: 'children',
                label: 'fullName',
                value: 'id'
            },
            listQuery: {
                currentPage: 1,
                pageSize: 200,
                pageType: JSON.stringify({
                    activeType: '1', //1列表模式 2 日程模式
                    startTime: '',
                    endTime: ''
                }),
                sort: 'desc',
                sidx: 'createtime',
                menuId: '455950455441204293',
                queryJson: ''
            },
            menuContent: [],
            config: {},
            columnData: {},
            list: [],
            sceneObjects: [],//记录标注对象，方便管理
            infoWindow: undefined,
        }
    },
    watch: {
        activeMenu: {
            handler: function () {
                console.log('activeMenu', this.activeMenu)
                if (this.activeMenu.moduleId == this.moduleId) return
                this.moduleId = ''
                this.treeData = []
                this.treeActiveId = ''
                this.clearObjects()
                if (this.activeMenu.moduleId)
                    this.getModuleInfo(this.activeMenu)
            },
            deep: true,
        }
    },
    beforeUnmount() {
        this.clearObjects()
    },
    mounted() {
        console.log('activeMenu', this.activeMenu)
        this.moduleId = ''
        this.treeData = []
        this.treeActiveId = ''
        this.clearObjects()
        if (this.activeMenu.moduleId) this.getModuleInfo(this.activeMenu)
        // this.xbsjEarthUi.activeViewer.pickedEvent.don(e => {
        //     console.log('viewer点击',e)
        //     if(e.childPickedInfo.attachedInfo.pointerEvent.type!="pointerdown") return
        //     //点击其他位置关闭信息窗口，需厂家更新
        //     if (this.infoWindow) this.destroyInfoWindow()
        // })
    },
    methods: {

        search(queryJson, flowState) {
            if (!queryJson && this.columnData.treeDataSource !== "flow") this.$refs.treeBox && this.$refs.treeBox.setCurrentKey(null);
            // this.listQuery.flowState = flowState//流程状态初始化
            this.listQuery.queryJson = queryJson
            this.listQuery.currentPage = 1
            this.initData()
        },
        handleNodeClick(data, node) {
            if (this.treeActiveId == data[this.treeProps.value]) return
            this.treeActiveId = data[this.treeProps.value]
            let queryJson = {}
            if (this.columnData.treeDataSource === "organize") {
                const nodePath = this.getNodePath(node)
                const currValue = nodePath.map(o => o[this.treeProps.value])
                queryJson = { [this.columnData.treeRelation]: currValue }
            } else if (this.columnData.treeDataSource === "flow") {
                this.listQuery.flowState = data[this.treeProps.value]
            } else {
                queryJson = { [this.columnData.treeRelation]: data[this.treeProps.value] }
                if (this.queryJson) {
                    Object.assign(queryJson, JSON.parse(this.queryJson))
                }
            }
            this.search(JSON.stringify(queryJson), this.listQuery.flowState)
        },
        getNodePath(node) {
            let fullPath = []
            const loop = (node) => {
                if (node.level) fullPath.unshift(node.data)
                if (node.parent) loop(node.parent)
            }
            loop(node)
            return fullPath
        },
        getTreeView() {

            if (this.columnData.treeDataSource === "dictionary") {
                if (!this.columnData.treeDictionary) return
                getDictionaryDataSelector(this.columnData.treeDictionary).then(res => {
                    this.treeData = res.data.list
                })
            }
            if (this.columnData.treeDataSource === "organize") {
                getDepartmentSelector().then(res => {
                    this.treeData = res.data.list
                })
            }
            if (this.columnData.treeDataSource === "department") {
                getDepartmentSelector().then(res => {
                    this.treeData = res.data.list
                })
            }

            if (this.columnData.treeDataSource === "flow") {
                this.listQuery.flowState = '1'
                this.treeData = [{
                    fullName: '草稿',
                    id: '-1'
                },
                {
                    fullName: '我发起的',
                    id: '0'
                },
                {
                    fullName: '待办',
                    id: '1'
                },
                {
                    fullName: '已办',
                    id: '2'
                },
                {
                    fullName: '抄送',
                    id: '3'
                },
                {
                    fullName: '办结',
                    id: '02'
                },
                    // {
                    //   fullName: '流程委托',
                    //   id: '3'
                    // },

                ]
                this.mescroll.resetUpScroll();
            }
            if (this.columnData.treeDataSource === "api") {
                if (!this.columnData.treePropsUrl) return
                getDataInterfaceRes(this.columnData.treePropsUrl).then(res => {
                    let data = res.data.data
                    if (Array.isArray(data)) {
                        this.treeData = data
                    } else {
                        this.treeData = []
                    }
                })
            }
            // this.treeData=[{
            //     [this.treeProps.value]:'00000',
            //     [this.treeProps.label]:this.activeMenu.label,
            //     [this.treeProps.children]:this.treeData

            // }]
            console.log(this.treeData)
        },
        // async getConfig(id) {
        //     await getConfig({
        //         id: id
        //     }).then(res => {
        //         let columnData = JSON.parse(res.data.columnData)
        //         this.checkModules[id].config.columnData = columnData
        //         return columnData
        //     })
        // },
        initData() {
            getList(this.moduleId, this.listQuery).then(res => {
                this.list = res.data.list
                this.$emit('updateMenuListData',{activeMenu:this.activeMenu,list:this.list,columnData:this.columnData})
                return
                this.$nextTick(()=>{
                    this.list.map(async (item,index)=>{
                        if(index!=0) return
                        let tags=['HEAD','LINK','STYLE']
                        let markerDom = this.$refs['markerDom-'+item.id][0].$el
                        let canvas = await html2canvas(markerDom, { backgroundColor: 'transparent',scale:3,ignoreElements: (element)=>{
                            if(element.compareDocumentPosition(markerDom)==20||element.getAttribute('name')=='markerDom'||tags.indexOf(element.tagName)!=-1){
                                return false
                            }else{
                                return true
                            }

                        } })

                        var imgData = canvas.toDataURL('image/png'); // 将生成的canvas转换为DataURL格式
                        item.$imgData = imgData
                        console.log(markerDom,canvas,imgData)

                    })
                    this.createSceneObject(this.moduleId)
                })
            })
        },

        contexMenuEvent(menu) {

            const baseItems = [
                {
                    text: "删除",
                    keys: "",
                    func: () => {
                        this.removeMenu(menu)
                    },
                },
            ];
            this.menuContent = baseItems
        },

        async getModuleInfo(menu) {
            // if(this.activeMenu.moduleId != menu.moduleId)return 

            // this.clearObjects()
            this.moduleId = menu.moduleId
            let configRes = await getConfig({ id: menu.moduleId })
            this.config = configRes.data
            this.columnData = JSON.parse(configRes.data.columnData)
            console.log(this.columnData)
            this.listQuery.sort = this.columnData.sort
            this.listQuery.sidx = this.columnData.defaultSidx
            if (this.columnData.type === 2) {
                this.treeProps.value = this.columnData.treePropsValue || 'id'
                this.treeProps.label = this.columnData.treePropsLabel || 'fullName'
                this.treeProps.children = this.columnData.treePropsChildren || 'children'
                this.getTreeView()
            }
            this.initData()
        },
        clearObjects() {
            this.sceneObjects.map(obj => {
                this.xbsjEarthUi.destroySceneObject(obj)
            })
            this.infoWindow && this.destroyInfoWindow()
            this.sceneObjects = []

        },
        destroyInfoWindow() {
            this.xbsjEarthUi.destroySceneObject(this.infoWindow)
            this.infoWindow = undefined
        },
        createInfoWindow(point) {
            console.log(point)
            if (this.infoWindow) this.destroyInfoWindow()
            let xbsjEarthUi = this.xbsjEarthUi
            let info = this.xbsjEarthUi.createSceneObject('ESGeoDiv')
            info.position = point.position
            info.anchor = [0.5,1.1]
            let _this = this

            // //复杂div设置
            class MyDiv {
                // container是Poi的div
                // eSGeoDiv指向当前的GeoCustomDivPoi场景对象
                // viewer指定当前的视口
                constructor(container, eSGeoDiv, viewer) {
                    this._container = container;
                    this._eSGeoDiv = eSGeoDiv
                    this._viewer = viewer
                    this._div = document.createElement('div');
                    this._container.appendChild(this._div);
                    this._div.className = `infoBox`;
                    this._div.style.width = xbsjEarthUi.infoWidth + 'px'
                    this._div.style.height = xbsjEarthUi.infoHeight + 'px'
                    this._divTitle = document.createElement('div');
                    this._divTitle.className = `infoBox-title`;
                    this._divTitle.innerHTML = `<div>${point.title}</div>`
                    this._divClose = document.createElement('div');
                    this._divClose.className = `infoBox-title-close`;
                    this._divClose.innerHTML = ` <span class="el-icon-close" ></span>`
                    this._divClose.addEventListener('click', () => { this.close(eSGeoDiv) })
                    this._divTitle.appendChild(this._divClose);
                    this._div.appendChild(this._divTitle);
                    this._divContent = document.createElement('div');
                    this._divContent.className = `infoBox-content`;
                    let contentHtml = ''
                    let videoMonitorInfo = []
                    point.subContent.map(sub => {
                        if (sub.jnpfKey == 'videoMonitor') {
                            // contentHtml+=`<div id='player'></div>`
                            videoMonitorInfo = sub.value ? JSON.parse(sub.value) : []
                            console.log('videoMonitorInfo', videoMonitorInfo)
                            if (videoMonitorInfo.length == 0) return
                            // point.videoiframeLinkurl = 'http://www.sinobroad.com:48080/#/play/wasm/ws%3A%2F%2F192.168.100.134%3A80%2Frtp%2F41010500002000000001_34020000001320000001.live.flv'
                            this._videoIframe = document.createElement('div');
                            this._videoIframe.className = `infoBox-iframe isCesium`;
                            // this._videoIframe.innerHTML = `<iframe src="http://127.0.0.1:8080${videoMonitorInfo[1]}?type=iframe" class='infoBox-iframe-body' scrolling='yes'/>`
                            this._videoIframe.innerHTML = `<div id='videoMonitor' class='infoBox-iframe-body'></div>`
                            this._div.appendChild(this._videoIframe);
                            // this._videoBtn = document.createElement('div');
                            // this._videoBtn.className = `infoBox-iframe-btn`;
                            // this._videoBtn.innerHTML = `查看`
                            // this._videoBtn.addEventListener('click', function () {
                            //     window.open(`http://127.0.0.1:8080${videoMonitorInfo[1]}`)
                            // })
                            // this._div.appendChild(this._videoBtn);
                            _this.$nextTick(() => {
                                this.create()
                                this.play(`${videoMonitorInfo[1]}`)
                            })

                            // console.log('videoMonitorInfo',videoMonitorInfo)

                        } else {
                            contentHtml += `<div>${sub.label}:${sub.value}</div>`
                        }
                    })
                    this._divContent.innerHTML = contentHtml
                    if (contentHtml) this._div.appendChild(this._divContent);


                    if (point.iframeLinkurl) {
                        this._divIframe = document.createElement('div');
                        this._divIframe.className = `infoBox-iframe`;
                        this._divIframe.innerHTML = `<iframe src=${point.iframeLinkurl} class='infoBox-iframe-body' scrolling='yes'/>`
                        this._div.appendChild(this._divIframe);

                    }
                }
                create(options) {
                    this.jessibuca = new window.Jessibuca(
                        {
                            container: document.getElementById('videoMonitor'),
                            decoder: "jessibuca/decoder.js",
                            isResize: false,
                            text: "",
                            // background: "bg.jpg",
                            loadingText: "疯狂加载中...",
                            debug: true,
                            supportDblclickFullscreen: true,
                            showBandwidth: true, // 显示网速
                            operateBtns: {
                                fullscreen: true,
                                screenshot: true,
                                play: true,
                                audio: true,
                            },
                            forceNoOffscreen: true,
                            isNotMute: true,
                            timeout: 10
                        }
                    );
                    var _this = this;
                    this.jessibuca.on("load", function () {
                        console.log("on load");
                    });

                    this.jessibuca.on("log", function (msg) {
                        console.log("on log", msg);
                    });
                    this.jessibuca.on("record", function (msg) {
                        console.log("on record:", msg);
                    });
                    this.jessibuca.on("pause", function () {
                        console.log("on pause");
                        _this.playing = false;
                    });
                    this.jessibuca.on("play", function () {
                        console.log("on play");
                        _this.playing = true;
                    });
                    this.jessibuca.on("fullscreen", function (msg) {
                        console.log("on fullscreen", msg);
                    });

                    this.jessibuca.on("mute", function (msg) {
                        console.log("on mute", msg);
                        _this.quieting = msg;
                    });

                    this.jessibuca.on("mute", function (msg) {
                        console.log("on mute2", msg);
                    });

                    this.jessibuca.on("audioInfo", function (msg) {
                        console.log("audioInfo", msg);
                    });

                    // this.jessibuca.on("bps", function (bps) {
                    //   // console.log('bps', bps);
                    // });
                    // let _ts = 0;
                    // this.jessibuca.on("timeUpdate", function (ts) {
                    //     console.log('timeUpdate,old,new,timestamp', _ts, ts, ts - _ts);
                    //     _ts = ts;
                    // });

                    this.jessibuca.on("videoInfo", function (info) {
                        console.log("videoInfo", info);
                    });

                    this.jessibuca.on("error", function (error) {
                        console.log("error", error);
                    });

                    this.jessibuca.on("timeout", function () {
                        console.log("timeout");
                    });

                    this.jessibuca.on('start', function () {
                        console.log('frame start');
                    })

                    this.jessibuca.on("performance", function (performance) {
                        var show = "卡顿";
                        if (performance === 2) {
                            show = "非常流畅";
                        } else if (performance === 1) {
                            show = "流畅";
                        }
                        _this.performance = show;
                    });
                    this.jessibuca.on('buffer', function (buffer) {
                        console.log('buffer', buffer);
                    })

                    this.jessibuca.on('stats', function (stats) {
                        console.log('stats', stats);
                    })

                    this.jessibuca.on('kBps', function (kBps) {
                        console.log('kBps', kBps);
                    });

                    this.jessibuca.on("play", () => {
                        this.playing = true;
                        this.loaded = true;
                        this.quieting = this.jessibuca.isMute();
                    });

                    this.jessibuca.on('recordingTimestamp', (ts) => {
                        console.log('recordingTimestamp', ts);
                    })


                    // console.log(this.jessibuca);
                }
                play(playUrl) {
                    if (playUrl) {
                        console.log(playUrl)
                        this.jessibuca.play(playUrl);
                    }
                }
                close(eSGeoDiv) {
                    console.log(this)
                    this.jessibuca && this.jessibuca.destroy()
                    if (_this.infoWindow) _this.destroyInfoWindow()
                }
                // 销毁函数，注意此函数必需，否则会报错！
                destroy() {
                    console.log('销毁窗口')
                    this.jessibuca && this.jessibuca.destroy()
                    // this._container.removeChild(this._div);
                }
            }
            info.instanceClass = MyDiv;

            // let renderHtml =
            //     `<div class="infoBox">
            //         <div class="infoBox-title">
            //             <div>${point.title}</div>
            //             <div class="infoBox-title-close" onclick="destroyInfoWindow()" >
            //                 <span class="el-icon-close" ></span>
            //             </div>
            //         </div>
            //         <div class="infoBox-content">`
            // point.subContent.map(sub=>{
            //     renderHtml+=`<div>${sub.label}:${sub.value}</div>`
            // })
            // renderHtml+=  `</div></div>`
            // info.innerHTML = renderHtml
            info.pickedEvent.don(e => {
                info.editing = false
            })
            this.infoWindow = info


            // info.show = false
        },
        createSceneObject(id) {
            this.clearObjects()
            let mapOptions = this.columnData.mapOptions //地图信息配置
            let markerStyle = this.columnData.markerStyle //标注风格
            let mapColorPlan = this.columnData.mapColorPlan //颜色方案
            let minLon = Infinity
            let maxLon = -Infinity
            let minLat = Infinity
            let maxLat = -Infinity
            console.log(this.activeMenu)

            this.list.forEach(element => {
                if (!element[mapOptions.lnglat]) return
                let position = []
                try {
                    position = [...JSON.parse(element[mapOptions.lnglat])]
                } catch (e) {
                    return
                    console.log(e)
                }

                if (position.length == 2) position.push(0)
                position = position.map(Number)
                // console.log('position',position)
                minLon = Math.min(minLon, position[0])
                maxLon = Math.max(maxLon, position[0])
                minLat = Math.min(minLat, position[1])
                maxLat = Math.max(maxLat, position[1])

                let point = this.xbsjEarthUi.createSceneObject('ESGeoDiv')
                point.moduleId = id
                point.dataId = element.id
                point.iframeLinkurl = element['Iframe_Linkurl'] ? element['Iframe_Linkurl'] + '?dataId=' + element.id : ''
                point.iframeLinkurl = point.iframeLinkurl.replace(/\${tb}/g,localStorage.getItem('jnpf_tburl')).replace(/\${tbToken}/g,localStorage.getItem('jnpf_tbtoken')).replace(/\${tbRefreshToken}/g, localStorage.getItem('jnpf_tbrefreshtoken'))
                point.position = position

                let subContent = []
                if (this.columnData.mapSubTitles && this.columnData.mapSubTitles.length > 0) {
                    this.columnData.mapSubTitles.map(subtitle => {
                        let columnInfo = this.columnData.columnList.find(item => { return item.prop == subtitle.value })
                        // console.log(columnInfo)
                        subContent.push({
                            jnpfKey: columnInfo.jnpfKey,
                            key: subtitle.value,
                            label: (columnInfo && columnInfo.label) || '-',
                            value: element[subtitle.value]
                        })
                    })
                }
                point.title = element[mapOptions.title]
                point.subContent = subContent

                let backgroundColor = markerStyle.backgroundColor

                if (mapOptions.useColorRules) {
                    this.$emit('updateColorPlan',{activeMenu:this.activeMenu,mapColorPlan:mapColorPlan,mapOptions:mapOptions})
                    mapColorPlan.map(item => {
                        // if(eval(Number(element[mapOptions.compareField])+item.compare+item.value)){
                        //     backgroundColor = item.backgroundColor
                        // }
                        let value = element[mapOptions.compareField]
						if(mapOptions.compareType == 1){
							if (item.max >= Number(value) && Number(value) > item.min) {
                            	backgroundColor = item.backgroundColor
                        	}
						}
						if(mapOptions.compareType == 2){
							if (item.value == value ) {
                            	backgroundColor = item.backgroundColor
                        	}
						}
                    })
                }

                let renderHtml =
                    ` 
                    <div class="marker">
                        <div class="markerStyle">
                            <div class="markerStyle-bg">
                                <div class="markerStyle-circle"  style="background: ${backgroundColor}"></div>
                                <div class="markerStyle-rect" style="background: ${backgroundColor}"></div>
                            </div>
                            <div class="markerStyle-icon"  style="color:${markerStyle.textColor}">`
                if (mapOptions.innerType == "field") {
                    renderHtml += element[mapOptions.innerField]
                } else {
                    renderHtml += `<i class="${markerStyle.icon}"></i>`
                }
                renderHtml +=
                    `</div>
                        </div>
                        <div class="markerStyle-text" title='${point.title}'>${point.title}</div>
                    </div>
                    `

                point.innerHTML = renderHtml
                point.allowPicking = true
                point.editing = false

                var that = this
                point.pickedEvent.don(e => {
                    point.editing = false
                    // point.scale = [2,2,2]
                    console.log(point)
                    console.log(e)
                    let data = {
                        type:'clickPoint',
                        pointInfo:{
                            moduleId : point.moduleId,
                            dataId:point.dataId
                        }
                    }
                    window.top.postMessage(JSON.stringify(data),'*')
                    //点击飞入到当前点位，需厂家更新
                    // point.flyTo()
                    if(this.xbsjEarthUi.ueIsShow){
                        that.$emit('updateActivePoint',point)
                    }else{
                        that.createInfoWindow(point)
                    }
                })
                this.sceneObjects.push(point)
            })

            if (minLon != Infinity && maxLon != -Infinity && minLat != Infinity && maxLat != -Infinity) {
                let rectangle = Cesium.Rectangle.fromDegrees(minLon, minLat, maxLon, maxLat)
                console.log(rectangle)
                if(this.xbsjEarthUi.cameraViewsManager.views.length>0)return
                // this.xbsjEarthUi.activeViewer.flyIn([(minLon+maxLon)/2,(minLat+maxLat)/2,5000])
                this.xbsjEarthUi.activeViewer.innerViewer.viewer.camera.flyTo({
                        destination:rectangle,
                        duration:1
                })
            }



        },

    },
}
</script>

<style>

.jnpf-tree-wrapper {
    width: 100%;
    /* height: 100%; */
    /* padding: 10px 10px 0 10px; */
    overflow: none;
    overflow-anchor: none;
}

.jnpf-tree-title {
    cursor: pointer;
    display: flex;
    align-items: center;
    font-size: 14px;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.custom-tree-node-content {
    flex: 1;
    display: flex;
    align-items: center;
    padding-right: 10px;
}
</style>

<style>
.hideMarker{
    position: fixed;
    left: 10px;
}
.marker {
    display: flex;
    flex-direction: column;
    position: relative;
}

.markerStyle-text {
    position: absolute;
    top: 48px;
    background: rgba(0, 0, 0, .7);
    color: #fff;
    line-height: 1.5em;
    font-size: 13px;
    white-space: nowrap;
    left: 50%;
    transform: translate(-50%);
    border-radius: 5px;
    padding: 0 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 180px;
}

.markerStyle {
    width: 36px;
    height: 44px;
    position: relative;
}

.markerStyle-bg {
    background: transparent;
    transform: rotate(45deg);
    width: 36px;
    height: 36px;
}

.markerStyle-icon {
    position: absolute;
    color: #fff;
    left: 50%;
    line-height: 38px;
    top: 0;
    transform: translate(-50%);
    font-size: 12px;
    /* overflow: hidden;
    white-space: nowrap;
    text-align: center; */
}

.markerStyle-circle {
    position: absolute;
    left: 0;
    top: 0;
    border-radius: 100%;
    width: 32px;
    height: 32px;
    border: 2px solid rgba(255, 255, 255, 1);
}

.markerStyle-rect {
    position: absolute;
    left: 16px;
    top: 16px;
    width: 18px;
    height: 18px;
    border-bottom: 2px solid rgba(255, 255, 255, 1);
    border-right: 2px solid rgba(255, 255, 255, 1);
}
</style>